import { defineConfig, loadEnv, createServer } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import MiniProgramTailwind from "@dcasia/mini-program-tailwind-webpack-plugin/rollup";
import path from "path";
import AutoImport from "unplugin-auto-import/vite";
import AutoComponent from "unplugin-vue-components/vite";
import { changeMpWeixinAppid } from "./lib/scriptBeforeboundle";

//静态资源服务器配置
const staticServerHost = "0.0.0.0",
  staticServerPort = 9008;

//本地静态资源服务器
const server = async () => {
  const server = await createServer({
    // 任何合法的用户配置选项，加上 `mode` 和 `configFile`
    configFile: false,
    root: __dirname,
    publicDir: path.resolve(__dirname, "./src/assets/images"),
    server: {
      host: staticServerHost,
    },
  });
  await server.listen(staticServerPort);
  server.printUrls();
};

//vite配置
export default defineConfig(({ mode }) => {
  let env = loadEnv(mode, ".");
  const isDev = process.env.NODE_ENV === "development";
  isDev && server();

  //根据不同的环境，修改manifest.json中的appid
  changeMpWeixinAppid(env.VITE_APPID);

  return {
    define: {
      //静态资源url
      __CDN_URL__: isDev
        ? JSON.stringify(`http://${staticServerHost}:${staticServerPort}`)
        : JSON.stringify(env.VITE_STATIC_BASEURL),
    },
    plugins: [
      uni(),
      //解决小程序不支持的类名，如*、jit模式生成的类名
      MiniProgramTailwind({
        enableRpx: true, //是否开启自动转换至 rpx 单位值的功能
      }),
      //自动引入api
      AutoImport({
        imports: [
          {
            "@/hooks/useGlobalVal": ["useGlobalVal"], // import {useGlobalVal} from "@/hooks/useGlobalVal"
            "@/hooks/useGetPageQuery": ["useGetPageQuery"], // import {useGetPageQuery} from "@/hooks/useGetPageQuery"
            "@/hooks/useGetNavInfo": [["default", "useGetNavInfo"]], // import {default as useGetNavInfo} from "@/hooks/useGetNavInfo"
            "@/hooks/useGetNavbarOpacity": ["useGetNavbarOpacity"], // import {useGetNavbarOpacity} from "@/hooks/useGetNavbarOpacity"
            "@/utils/helper": [["*", "helper"]], // import {default as helper} from "@/utils/helper"
            "@/utils/typeIs": [["*", "typeIs"]], // import {* as typeIs} from "@/utils/typeIs"
            "@/utils/interaction": [["*", "interaction"]], // import {* as interaction} from "@/utils/interaction"
            "@/utils/utils": [["*", "utils"]], // import {* as utils} from "@/utils/utils"
            "@/utils/request": [["*", "request"]], // import {* as request} from "@/utils/request"
          },
        ],
      }),
      //自动引入组件
      AutoComponent({
        globs: ["src/components/g-*.{vue}"],
      }),
    ],
    css: {
      postcss: {
        plugins: [
          require("tailwindcss")({
            config: require("./tailwind.config.js"),
          }),
          require("autoprefixer")(),
          //将css中的url内容替换成正确的url
          require("postcss-url")({
            url: (asset) => {
              if (asset.url.startsWith("/")) {
                if (isDev) {
                  //本地开发用本地的静态资源服务
                  return `http://${staticServerHost}:${staticServerPort}${asset.url}`;
                } else {
                  //非本地环境用cdn
                  return `${env.VITE_STATIC_BASEURL}${asset.url}`;
                }
              }
              return asset.url;
            },
          }),
        ],
      },
    },
  };
});
